$(function(){

  if(!$('body').hasClass('admin-innoawards-partners')){ return; };

  var categories = gon.listPartners.categories === '' ? [] : gon.listPartners.categories.split(',');
  var detail = gon.listPartners.detail;
  var allPartners = gon.partners;

  var $updateState = $('#updateState');

  var getPartners = function(ids){
    if(ids === '') return [];
    var partners = [];
    ids.split(',').forEach(function(id){
      var p = allPartners.find(function(e){ return e.id === id });
      if(typeof p === 'undefined') return;
      partners.push({id: p.id, name: p.name});
    });
    return partners;
  };

  var getPartnerIDs = function(partners){
    if(partners === []) return '';
    var ids = [];
    partners.forEach(function(e){
      ids.push(e.id);
    });
    return ids.join(',');
  };

  var updatePartnersData = function(categories, detail){
    $.ajax({
      type: 'post',
      url: location.href,
      data: {categories: categories, detail: JSON.stringify(detail)},
      beforeSend: function(){
        $updateState.text('正在更新');
        $updateState.removeClass('positive');
        $updateState.addClass('warning');
        $updateState.show();
      },
      success: function(){
        $updateState.removeClass('warning');
        $updateState.addClass('positive');
        $updateState.text('更新完成');
        $updateState.hide(1000);
      }
    });
  };

  var listCategories = new Vue({
    el: '#list-categories',
    data: {
      categories: categories,
      selectedCategory: '',
      newCategory: ''
    },
    methods: {
      addNewCategory: function(){
        if(this.newCategory === '') return;
        this.categories.push(this.newCategory);
        listPartners.detail.$add(this.newCategory, '');
      },
      removeCategory: function(index){
        listPartners.detail.$delete(this.categories[index]);
        this.categories.splice(index, 1);
      },
      orderCategories: function(){
        var newOrder = [];
        $(this.$$.cList).children().each(function(index, e){
          newOrder.push($(e).data('name'));
        });
        this.categories = newOrder;
      },
      selectCategory: function(index){
        this.selectedCategory = this.categories[index];
        listPartners.selectedCategory = this.selectedCategory;
        listPartners.partners = getPartners(listPartners.detail[this.selectedCategory]);
        mountDropdown();
        mountPopup();
      },
      updateData: function(){
        updatePartnersData(this.categories.join(','), listPartners.detail);
      }
    },
    watch: {
      'categories': 'updateData'
    },
    attach: mountMovable()
  });

  var listPartners = new Vue({
    el: '#list-partners',
    data: {
      partners: [],
      selectedPartners: [],
      detail: detail,
      allPartners: allPartners,
      selectedCategory: ''
    },
    methods: {
      addNewPartners: function(){
        this.selectedPartners = getPartners($(this.$$.selectedPartnerIDs).val());
        this.partners = this.partners.concat(this.selectedPartners);
        this.detail[listCategories.selectedCategory] = getPartnerIDs(this.partners);
        this.updateData();
        this.$$.selectedPartnerIDs.value = '';
        $(this.$$.selectedPartnerIDs).parent().children('a').each(function(i, e){
          e.remove();
        });
      },
      removePartner: function(index){
        this.partners.splice(index, 1);
        this.detail[listCategories.selectedCategory] = getPartnerIDs(this.partners);
        this.updateData();
      },
      orderPartners: function(){
        var newOrder = [];
        $(this.$$.pList).children().each(function(index, e){
          newOrder.push($(e).data('id'));
        });
        this.detail[listCategories.selectedCategory] = newOrder.join(',');
        this.partners = getPartners(this.detail[listCategories.selectedCategory]);
        this.updateData();
      },
      returnCategories: function(){
        this.selectedCategory = '';
        listCategories.selectedCategory = this.selectedCategory;
      },
      updateData: function(){
        updatePartnersData(listCategories.categories.join(','), this.detail);
      },
      refreshSelectablePartners: function(){
        var res = $.get('/admin/partners/refresh', function(e){
          if(e.result === 'success'){
            alert('更新合作伙伴列表成功');
            location.href = location.href;
          } else {
            alert('更新合作伙伴列表失败，请联系管理员');
          }
        });
      }
    },
    attach: function(){
      mountDropdown();
      mountMovable();
    },
    filters: {
      selectable: function(value){
        if(this.selectedCategory === '') return [];
        var partnerIDs = this.detail[this.selectedCategory];
        return value.filter(function(e){
          return !partnerIDs.includes(e.id);
        });
      }
    }
  });

  function mountDropdown(){
    $('.ui.dropdown').dropdown();
  };

  function mountMovable(){
    $('.movable').bind('mouseover', function(){
      $(this).css('cursor', 'move');
    });
  };

  function mountPopup(){
    $('.ui.button.should-pop').popup();
  };

  $(listCategories.$$.cList).sortable({
    opacity: 0.6,
    revert: true,
    cursor: 'move',
    handle: '.movable',
    placeholder: 'movable-placeholder',
    helper: fixHelper,
    update: function() {
      listCategories.orderCategories();
    }
  });

  $(listPartners.$$.pList).sortable({
    opacity: 0.6,
    revert: true,
    cursor: 'move',
    handle: '.movable',
    placeholder: 'movable-placeholder',
    helper: fixHelper,
    update: function() {
      listPartners.orderPartners();
    }
  });

  var fixHelper = function(e, ui) {
    ui.children().each(function() {
      $(this).width($(this).width());
    });
    return ui;
  };
});
